﻿using System;
using System.Collections.Generic;
using System.Text;

namespace TTLL.Asm
{
    public class ToBin
    {
        public static bool Write5BitTypeAndData(System.IO.BinaryWriter writer, byte type,  UInt16 length,  byte[] writedata)
        {
            if (type > 0x1f) return false;
            if (length > 0 && writedata == null) return false;
            if (length > 0 && writedata.Length < length) return false;
            byte taglen = 0;
            if (length == 0) taglen = 0;
            else if (length == 1) taglen = 1;
            else if (length == 2) taglen = 2;
            else if (length == 4) taglen = 3;
            else if (length == 8) taglen = 4;
            else if (length == 16) taglen = 5;
            else if (length < 256) taglen = 6;// 3 5 6 7 9 ~15 都走這裏
            else if (length >= 256) taglen = 7;

            byte data = (byte)(((byte)(type << 3)) | (byte)taglen);
            writer.Write(data);
            if(taglen==6)
            {
                byte blen = (byte)length;
                writer.Write(blen);
            }
            else if(taglen==7)
            {
                writer.Write(length);//16bit length
            }
            if (length > 0)
            {
                writer.Write(writedata, 0, length);
            }
            return true;
        }
        public static byte[] SaveModule(Module module)
        {
            using (var ms = new System.IO.MemoryStream())
            {
                using (var writer = new System.IO.BinaryWriter(ms))
                {
                    module.WriteAll(writer);
                }
                return ms.ToArray();
            }
        }
    }
}
